import { useCallback, useEffect, useState } from "react";

const useSyncCallback = (callback) => {
  const [proxyState, setProxyState] = useState({ current: false });
  const [latestValues, setLatestValues] = useState([]);

  const Fun = useCallback(
    (...args) => {
      setProxyState({ current: true });
      setLatestValues(args);
    },
    [proxyState]
  );

  useEffect(() => {
    if (proxyState.current === true) setProxyState({ current: false });
  }, [proxyState]);

  useEffect(() => {
    proxyState.current && callback(...latestValues);
  });
  return Fun;
};

export default useSyncCallback;
